package com.zzyl.nursing.service.impl;


import java.util.HashMap;

import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 老人家属Service业务层处理
 * 
 * @author zhangshiyu
 * @date 2025-09-21
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LoginVo login(UserLoginRequestDto dto) {
        //1.根据code调用微信api获取apenId
        String openid = wechatService.getOpenid(dto.getCode());
        //2.根据openId查询数据库获取用户信息family_member表
        //select * from family_member where open_id = ?
        FamilyMember familyMember = lambdaQuery().eq(FamilyMember::getOpenId, openid).one();

        //3.判断用户信息是否存在，如果不存在，则准备新增，设置openid
        if(familyMember==null){
            familyMember = new FamilyMember();
            familyMember.setName(dto.getNickName());
            familyMember.setOpenId(openid);
        }
        //4.调用微信api获取用户绑定手机号
        String phone = wechatService.getPhone(dto.getPhoneCode());
        familyMember.setPhone(phone);
        //5.新增或者修改family_member表数据
        saveOrUpdate(familyMember);
        //数据库增删改交互完毕后下面仍有代码，要添加事物回滚
        //6.将用户id存入token中，并返回数据给前端
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userId",familyMember.getId());
        claims.put("name",familyMember.getName());
        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(familyMember.getName());
        loginVo.setToken(token);

        return loginVo;
    }
}
